$(document).ready(function() {
  $('.ad_status_edit').click(function() {
    var caller = $(this);
    editBtnHandler(caller);
    return false;
  });
});

function editBtnHandler(caller) {
  var parent = caller;
  $.get(caller.attr('href'),function(data){
    try {
      if (data.error) {
        throw data.error;
      }
      parent.after(data);
      $('#ad_status_edit_cancel').click(function() {
        $('#AbmAdStatusEditForm').remove();
        return false;
      });

      $('#ad_status_edit_save').click(function() {
        var status = $('#AdStatus').val();
        var href = $(this).attr('href');
        var confirm = $(this).attr('confirm');
        if (status == 'removed' || status == 'stopped') {
          needConfirm(confirm, href, status, parent);
        } else {
          changeStatus(href, status, parent);
        }

        $('#AbmAdStatusEditForm').remove();
        return false;
      });
    } catch(exception) {
      makeErrorMessage(exception);
    }
  });
}

function needConfirm(confirmURL, targetURL, status, offsetParent) {
  popupHandler.get().load({
    url: confirmURL, //+ '/' + status,
    offsetParent:offsetParent,
    callback: function() {
      $("a.confirm").unbind("click");
      $("a.confirm").click(function() {
        changeStatus(targetURL, status, offsetParent);
        popupHandler.get().remove();
        offsetParent.parents("tr").remove();
        return false;
      });
    },
    horizon:'center',
    vertical:'middle'
  });
}

function changeStatus(url, status, view) {
  $.getJSON(url + '/status/' + status, function(data){
    if (!data.error) {
      if ($('img.ad_status_em',view).length != 0) {
        $('img.ad_status_em',view).attr('src', '/img/ads/' + data.Ad.status + '.gif');
        $('span.ad_status_em',view).html(data.Ad.status);
      } else {
        $('img.ad_status_em').attr('src', '/img/ads/' + data.Ad.status + '.gif');
        $('span.ad_status_em').html(data.Ad.status);
      }
    } else {
      makeErrorMessage(data.error);
    }
  });
}